#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   app.py
@Time    :   2020/09/28 11:08:32
@Author  :   fengzhilaoling 
@Version :   1.0
@Contact :   fengzhilaoling@163.com
'''
from flask import Flask
from redis import Redis
from uuid import uuid4
from flask import jsonify
from flask import request


class config:  # 配置类
    HOST = '39.96.7.141'  # redis服务器地址
    PORT = 6379  # redis端口
    EXPIRE_TIME = 60  # token过期时间
    DEBUG = True


class RedisDB:
    def __init__(self, host, port, password=''):
        self.conn = Redis(  # redis连接
            host=host,
            port=port,
            password=password
        )

    # token保存函数
    def set_redis_token(self, key, value):
        result = self.conn.set(key, value, ex=config.EXPIRE_TIME)
        return result

    # token获取函数
    def get_redis_token(self, key):
        result = self.conn.get(key)
        if result:
            return result
        else:
            return '0'

app = Flask(__name__)
app.config.from_object(config)
redis = RedisDB(host=config.HOST, port=config.PORT)  # redis连接对象


# 设置token函数
def set_token(user_name):
    token = str(uuid4())
    result = redis.set_redis_token(key=token, value=user_name)
    return result, token


@app.route('/login/', methods=['POST'])
def login():
    # 登陆传入用户名密码
    user_name = request.json.get('username')  
    password = request.json.get("password")
    if user_name == 'fengling' and password == 'tian':
        result, token = set_token(user_name=user_name)  # 调用保存token方法，保存token
        if result:  # 保存是否成功
            data = {
                'code': 0,
                'msg': 'success'
            }
            # 生产中前端需要，把状态和token存储下来
            return jsonify(data), {'token': token, 'login_status': 1}  # 返回保存成功内容，并将token和登陆状态给header
        else:
            return jsonify({'code': 5001, 'msg': 'redis添加失败！'})
    else:
        return jsonify({'code': 4004, 'msg': '用户名或密码错误！'})


@app.route('/index/')
def index():
    token = request.headers['token']  # 获取请求header中的token
    user_name = redis.get_redis_token(token)   # 获取token中的值
    if user_name != '0':
        # 通过用户名，查询数据库中的user的对应信息
        data = {
            'code': '0',
            'sex':'男',
            # 等等
            'msg': 'success',
            'user_name': str(user_name),
        }
        return jsonify(data)  # 返回结果
    else:
        return jsonify({'msg': 'token错误'}), {'login_status': '0'}



if __name__ == "__main__":
    app.run()
